package com.lzy.srb.core.controller.admin;

import com.alibaba.excel.EasyExcel;
import com.lzy.common.exception.BusinessException;
import com.lzy.common.result.R;
import com.lzy.common.result.ResponseEnum;
import com.lzy.srb.core.pojo.dto.ExcelDictDTO;
import com.lzy.srb.core.pojo.entity.Dict;
import com.lzy.srb.core.service.DictService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;


@RestController
@RequestMapping("/admin/core/dict")
//@CrossOrigin
@Api(tags="数据字典管理")
public class AdminDictController {

    @Autowired
    DictService dictService;

    @ApiOperation("Excel批量导入")
    @PostMapping("/import")
    public R batchImport (
            @RequestParam("file") MultipartFile file) throws Exception{
        try {
            InputStream inputStream = file.getInputStream();
            dictService.importData(inputStream);
        } catch (IOException e) {
            throw new BusinessException(ResponseEnum.UPLOAD_ERROR,e);
        }
        return R.ok().message("数据字典批量导入成功");
    }


    @ApiOperation("Excel数据的导出")
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("mydict", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), ExcelDictDTO.class).sheet("数据字典").doWrite(dictService.listDictData());
    }

    @GetMapping("/listByParentId/{parentId}")
    public R listByParent(@PathVariable("parentId")Long parentId){
        List<Dict> dictList =  dictService.listByParentId(parentId);
        return R.ok().data("list",dictList);
    }

}
